package com.sky.aspect;

import com.sky.exception.UpLoadFileException;
import com.sky.myannotation.FilterTypeUploadFile;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Component
@Aspect
@Log4j2
public class FilterTypeUploadFileAspect {

    @Pointcut("execution(* com.sky.controller.admin.CommonController.upload(..)) && @annotation(com.sky.myannotation.FilterTypeUploadFile)")
    public void fileTpyePointcut(){
    }

    @Before("fileTpyePointcut()")
    public void fileTypeBefore(JoinPoint joinPoint){
        log.info("文件上传类型过滤");
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        FilterTypeUploadFile annotation = methodSignature.getMethod().getAnnotation(FilterTypeUploadFile.class);
        List<String> list = Arrays.asList(annotation.types());

        Object[] args = joinPoint.getArgs();
        if(args == null || args.length == 0){
            return;
        }
        MultipartFile multipartFiles = (MultipartFile) args[0]; // 获取文件上传文件对象
        String substring = multipartFiles.getOriginalFilename().substring(multipartFiles.getOriginalFilename().lastIndexOf("."));
        System.out.println(list);
        if(!list.contains(substring)){
            // 不存在
            throw new UpLoadFileException("文件类型不正确");
        }
    }
}
